<template>
  <v-container fluid>
    <v-row>
      <v-col cols="12">
        <v-data-table
            :headers="headers"
            :items="userReports"
            item-key="rid"
            class="elevation-1"
            disable-filtering
            disable-sort
            show-expand
            :loading="loading"
            :options.sync="options"
            :server-items-length="total"
            loading-text="正在加载~"
            no-data-text="没有数据"
            no-results-text="找不到哦"
            :footer-props="{itemsPerPageAllText:'所有',itemsPerPageText:'每页条数'}"
        >
          <template v-slot:top>
            <v-toolbar flat color="secondary">
              <v-toolbar-title>用户投诉管理</v-toolbar-title>
              <v-row class="mt-4">

                <v-col cols="4" offset="4">
                  <v-select height="20"
                            dense
                            clearable
                            outlined
                            label="处理状态"
                            v-model="formSearch.process"
                            :items="processStatus"
                            item-text="value"
                            item-value="key"
                  ></v-select>
                </v-col>
                <v-col cols="4">
                  <v-select height="20"
                            dense
                            clearable
                            outlined
                            label="投诉类型"
                            v-model="formSearch.reason"
                            :items="reasons"
                            item-text="valueName"
                            item-value="value"
                  >
                    <template v-slot:append-outer>
                      <v-icon @click="doSearchReport">
                        mdi-magnify
                      </v-icon>
                    </template>
                  </v-select>
                </v-col>
              </v-row>

            </v-toolbar>
          </template>
          <template v-slot:item.actions="{ item }">
            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-icon v-bind="attrs"
                        v-on="on"
                        class="mr-2"
                        @click="openEditMessage(item)"
                >
                  mdi-pencil
                </v-icon>
              </template>
              <span>修改</span>
            </v-tooltip>

            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-icon v-bind="attrs"
                        v-on="on"
                        class="mr-2"
                        @click="openDelMessage(item)"
                >
                  mdi-delete
                </v-icon>
              </template>
              <span>删除</span>
            </v-tooltip>

          </template>
          <template v-slot:expanded-item="{ headers, item }">
            <!--            子菜单 表格-->
            <td :colspan="headers.length" class="pa-3" v-text="item.content">

            </td>
          </template>
        </v-data-table>
      </v-col>
    </v-row>
    <!--    添加新消息-->
    <v-dialog
        v-model="AddNewMessageDialog"
        max-width="800px"
    >
      <v-card>
        <v-card-title>
          添加新消息
        </v-card-title>
        <v-card-text class="pb-0">
          <v-text-field height="20"
                        dense
                        v-model="formNew.title"
                        outlined
                        label="消息标题"
                        ref="titleNew"
                        :rules="[rules.required,rules.maxLength(25)]"
                        counter="25"
          >
          </v-text-field>
        </v-card-text>
        <v-card-text>
          <quill-editor
              v-model="contentNew"
              :options="editorOption"
              class="editor"
              ref="myQuillEditor"
              @change="onChange"
          />
          <div class="v-counter theme--light text-right mt-2 " :class="contentCounter>300?'red--text':''">
            {{ contentCounter }} / 300
          </div>
        </v-card-text>
        <v-card-actions>
          <v-btn color="grey" class="ml-auto mr-2" dark @click="AddNewMessageDialog = false">取消</v-btn>
          <v-btn color="secondary" class="mr-2" dark @click="doAddNewMessage(false)">仅保存</v-btn>
          <v-btn color="primary" class="mr-2" dark @click="doAddNewMessage()">保存并发布</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!--    修改消息-->
    <v-dialog
        v-model="EditMessageDialog"
        max-width="800px"
    >
      <v-card>
        <v-card-title>
          修改消息
        </v-card-title>
        <v-card-text class="pb-0">
          <v-text-field height="20"
                        dense
                        v-model="formEdit.title"
                        outlined
                        label="消息标题"
                        ref="titleEdit"
                        :rules="[rules.required,rules.maxLength(25)]"
                        counter="25"
          >
          </v-text-field>
        </v-card-text>
        <v-card-text>
          <quill-editor
              v-model="contentEdit"
              :options="editorOption"
              class="editor"
              ref="myQuillEditor2"
              @change="onChange"
          />
          <div class="v-counter theme--light text-right mt-2 " :class="contentCounter>300?'red--text':''">
            {{ contentCounter }} / 300
          </div>
        </v-card-text>
        <v-card-actions>
          <v-btn color="grey" class="ml-auto mr-2" dark @click="EditMessageDialog = false">取消</v-btn>
          <v-btn color="secondary" class="mr-2" dark @click="doSaveMessage(false)">仅保存</v-btn>
          <v-btn color="primary" class="mr-2" dark @click="doSaveMessage()">保存并发布</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!--    删除消息-->
    <v-dialog
        v-model="DelMessageDialog"
        max-width="800px"
    >
      <v-card>
        <v-card-title>
          确认删除该条消息吗？
        </v-card-title>
        <v-card-actions>
          <v-btn color="grey" class="ml-auto mr-2" dark @click="DelMessageDialog = false">取消</v-btn>
          <v-btn color="red" dark @click="doDelMessage()">删除</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script>
import {simpleCopy, rules, myDateFormat} from "../../util/util";
import {baseUrl, imgPrefixUrl} from "../../myConfig";
import {Quill} from "vue-quill-editor";
import {ImageExtend, QuillWatch} from "quill-image-super-solution-module";
import {printMsg, utf8_to_b64, b64_to_utf8} from "../../util/util";

Quill.register("modules/ImageExtend", ImageExtend);

export default {
  name: "UserReportManage",
  data: () => ({
    rules: rules,
    AddNewMessageDialog: false,
    EditMessageDialog: false,
    DelMessageDialog: false,

    searchMessage: '',
    processStatus: [{key:'0',value:'未处理'},{key:'1',value:'已驳回'},{key:'2',value:'已处理'}],

    headers: [
      {text: '记录ID', value: 'rid', align: 'center', sortable: false},
      {text: '发布者', value: 'nickname', align: 'center', sortable: false},
      {text: '投诉类型', value: 'reasonValue', align: 'center', sortable: false},
      {text: '投诉内容', value: 'contentStr', align: 'center', sortable: false},
      {text: '当前状态', value: 'process', align: 'center', sortable: false},
      {text: '创建时间', value: 'createTime', align: 'center', sortable: false},
      {text: '操作', value: 'actions', align: 'center', sortable: false,},
      {text: '详细内容', value: 'data-table-expand', align: 'center', sortable: false,},
    ],
    userReports: [],
    reasons:[],
    options: {},
    total: 0,
    loading: false,

    formDel: {
      mid: ""
    },

    formSearch: {
      process: '',
      reason: '',
    },

    formNew: {
      title: '',
      content: '',
      type: 'type_admin',
      fromUid: '',
      toUid: "ALL",
    },
    formEdit: {
      content: '',
      title: '',
      mid: '',
    },

    contentNew: '',
    contentEdit: '',

    contentCounter: 0,
    content: '',
    // 富文本框参数设置
    editorOption: {
      modules: {
        ImageExtend: {
          loading: true,
          name: "img",
          size: 5,
          action: baseUrl + "file/saveImageFD",
          accept: "image/jpg, image/png, image/gif, image/jpeg",
          response: (res) => {
            printMsg(res, this)
            return baseUrl + imgPrefixUrl + res;
          },
          headers: (xhr) => {
            xhr.setRequestHeader("Authorization", window.localStorage.getItem("token"));
          },
          sizeError: () => {
            alert("图片大小超过 5 M");
          },

        },
        toolbar: {
          container: [
            [{'size': ['small', false, 'large']}],
            ['bold', 'italic'],
            [{'header': 1}, {'header': 2}],
            [{'list': 'ordered'}, {'list': 'bullet'}],
            [{'color': []}, {'background': []}],
            [{'align': []}],
            ['clean'],
            ["link", "image", "video"]
          ],
          handlers: {
            image: function () {
              QuillWatch.emit(this.quill.id);
            },
          },

        },
      }
    }
  }),
  watch: {
    options: {
      handler() {
        this.doSearchReport()
      },
      deep: true,
    },
  },
  methods: {
    processContent(content) {
      printMsg(content, this, "处理前传入")
      if (this.contentCounter > 300) {
        this.$emit('toast', '文章内容太长啦')
        return
      } else if (this.contentCounter === 0) {
        this.$emit('toast', '文章内容不能为空')
        return
      }
      // 处理content中的图片和链接的url
      content = content.replace('target="_blank"', 'target="_self"')
      content = content.replace(baseUrl + imgPrefixUrl, '')

      content = utf8_to_b64(content)
      return content
    },
    onChange(val) {
      this.contentCounter = val.quill.getLength() - 1
    },
    doSearchReport() {
      this.loading = true
      const {sortBy, sortDesc, page, itemsPerPage} = this.options

      let data = this.formSearch
      this.$http.post('report/listReports', data).then(res => {
        this.userReports = res.data || []
        this.userReports.map(item => {
          if (item.content) {
            item.content = b64_to_utf8(item.content)
            item.contentStr = item.content.length > 10?item.content.substr(0,10)+'......':item.content
            item.createTime = myDateFormat(item.createTime)
          }
          item.process = this.processStatus.filter(i=>(i.key === item.process))[0].value
        })
        this.loading = false
        this.total = res.total
      }).catch(res => {
        this.$emit('toast', res.msg)
        this.loading = false
      })
    },

    openDelMessage(item) {
      simpleCopy(item, this.formDel)
      this.DelMessageDialog = true
    },
    openEditMessage(item) {
      simpleCopy(item, this.formEdit)
      this.contentEdit = item.content
      this.EditMessageDialog = true
    },

    doDelMessage() {
      let data = {
        mid: this.formDel.mid,
      }
      this.$http.post('message/deleteMessage', data).then(res => {
        this.$emit('toast', '删除成功')
        this.DelMessageDialog = false
        this.doSearchMessage()
      }).catch(res => {
        this.$emit('toast', res.msg)
        this.DelMessageDialog = false
      })
    },
    doAddNewMessage(commit = true) {
      if (!this.$refs['titleNew'].validate(true)) return

      let content = this.processContent(this.contentNew)
      printMsg(content, this, '编码后的内容')

      if (!commit) this.formNew.status = 3
      let data = this.formNew
      data.content = content
      this.$http.post('message/addMessage', data).then(res => {
        this.$emit('toast', '新增成功')
        this.AddNewMessageDialog = false
        this.doSearchMessage()
      }).catch(res => {
        this.$emit('toast', res.msg)
        this.AddNewMessageDialog = false
      })
    },
    doSaveMessage(commit = true) {
      if (!this.$refs['titleEdit'].validate(true)) return

      let content = this.processContent(this.contentEdit)
      printMsg(content, this, '编码后的内容')

      if (!commit) this.formEdit.status = 3
      let data = this.formEdit
      data.content = content
      this.$http.post('message/updateMessage', data).then(res => {
        this.$emit('toast', '修改成功')
        this.EditMessageDialog = false
        this.doSearchMessage()
      }).catch(res => {
        this.$emit('toast', res.msg)
        this.EditMessageDialog = false
      })
    },
    doChangeStatus(item, status) {
      let data = {
        mid: item.mid,
        status: status
      }
      this.$http.post('message/updateMessage', data).then(res => {
        this.$emit('toast', status === 1 ? '发布成功' : '取消发布成功')
        this.doSearchMessage()
      }).catch(res => {
        this.$emit('toast', res.msg)
      })
    },
    getKeyValues(key, store) {
      let data = {
        key: key
      }
      this.$http.post('constant/listConstant', data).then(res => {
        this[store] = res.data[0].values
      }).catch(res => {
        this[store] = []
      })
    },
  },
  mounted() {
    this.getKeyValues('reportReason','reasons')
  }
}
</script>

<style scoped>

</style>
